package com.ruoyi.collection.process;

import com.alibaba.fastjson.JSON;
import com.ruoyi.bizsys.domain.LoanIou;
import com.ruoyi.bizsys.domain.RealNameAuth;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.bizsys.service.IRealNameAuthService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.collection.domain.ApiParameter;
import com.ruoyi.collection.domain.QueryDefaultOverDueInterestListReq;
import com.ruoyi.collection.domain.QueryDefaultOverDueInterestListResp;
import com.ruoyi.collection.process.api.CollectionProcess;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询逾期罚息
 * @author Victor
 *
 */
@Slf4j
@Service("QueryDefaultOverDueInterestList")
public class QueryDefaultOverDueInterestListPorcessor implements CollectionProcess {
	
	@Autowired
    private IRealNameAuthService realNameAuthService;
	
	@Autowired
	private ILoanIouService loanIouService;

	@Override
	public Object process(ApiParameter req) throws Exception {
		
		log.info("查询逾期罚息开始");
		
		QueryDefaultOverDueInterestListReq reqBody = JSON.parseObject(req.getBody().toString(), QueryDefaultOverDueInterestListReq.class);
		QueryDefaultOverDueInterestListResp respBody = new QueryDefaultOverDueInterestListResp();
		List<BigDecimal> penaltyInterestArray = new ArrayList<BigDecimal>();
		respBody.setPenaltyInterestArray(penaltyInterestArray);
		
		// 获取所有custNo
		RealNameAuth realNameAuthCondition = new RealNameAuth();
		realNameAuthCondition.setBvnAccount(reqBody.getCustId());
		realNameAuthCondition.setState(BizConstants.BIZ_STATUS_1);
		List<RealNameAuth> realNameAuthList = realNameAuthService.selectRealNameAuthList(realNameAuthCondition);
		if (CollectionUtils.isEmpty(realNameAuthList)) {
			log.info("无实名信息,查询逾期罚息结束");
			return respBody;
		}
		List<String> custNos = new ArrayList<String>();
		List<LoanIou> loanIouList = new ArrayList<LoanIou>(); 
		
		// 获取借据信息
		for(RealNameAuth realNameAuth : realNameAuthList){
			if(custNos.contains(realNameAuth.getCustNo())){
				continue;
			}
			custNos.add(realNameAuth.getCustNo());
			LoanIou loanIouCondition = new LoanIou();
			loanIouCondition.setCustNo(realNameAuth.getCustNo());
			loanIouCondition.setIouStatus(LoanIou.LOAN_IOU_STATUS_OVERDUE);
			loanIouCondition.setState(BizConstants.BIZ_STATUS_1);
			List<LoanIou> loanIous = loanIouService.selectLoanIouList(loanIouCondition);
			if (CollectionUtils.isNotEmpty(loanIous)) {
				loanIouList.addAll(loanIous);
			}
		}
        
        if (CollectionUtils.isEmpty(loanIouList)) {
        	log.info("无逾期借据信息,查询逾期罚息结束");
        	return respBody;
        }
        getPenaltyInterestArray(loanIouList, penaltyInterestArray);
		
		log.info("查询逾期罚息结束");
		return respBody;
		
	}

	private void getPenaltyInterestArray(List<LoanIou> loanIouList, List<BigDecimal> penaltyInterestArray) throws Exception {
		
		// 固定计算25天罚息
		for(int i = 1; i <= 25; i++){
			
			Date batchDate = DateUtils.addDays(new Date(), i);
			Instant batchDateInstant = batchDate.toInstant();
			BigDecimal lateFee = BigDecimal.ZERO;
			
			for(LoanIou loanIou : loanIouList){
				
				// 排除2021.05.26之前的数据
				Date startCollectDate = DateUtils.parseDate("2021-05-26 00:00:00", DateUtils.YYYY_MM_DD_HH_MM_SS);
				if(loanIou.getCreateTime().before(startCollectDate)){
					continue;
				}
				
				//还款日
		        Date repayDate = DateUtils.parseDate(loanIou.getRepayDate(), DateUtils.YYYY_MM_DD_SLASH);
		        
		        //逾期天数计算
		        Instant repayDateInstant = repayDate.toInstant();
		        long daysDiff = Duration.between(repayDateInstant, batchDateInstant).toDays();

		        //判断是否在宽限期
		        int lateFeeGracePeriod = loanIou.getLateFeeGracePeriod();
		        if (daysDiff > lateFeeGracePeriod) {
		            daysDiff = daysDiff - lateFeeGracePeriod;
		        }

		        //计算滞纳金
		        if (daysDiff > 0) {
		            BigDecimal principalNeed = loanIou.getLoanPrincipal().subtract(loanIou.getRepaidPrincipal());//本金还需要还的

		            //滞纳金日费率
		            BigDecimal dateLateFee = loanIou.getDateLateFee();

		            //费率计算的最大天数
		            if (loanIou.getLateFeeMaxDays() < daysDiff) {
		                daysDiff = loanIou.getLateFeeMaxDays();
		            }

		            //计算滞纳金
		            lateFee = lateFee.add(principalNeed.multiply(dateLateFee).multiply(new BigDecimal(daysDiff)));
		            		
		        }
			}
			penaltyInterestArray.add(lateFee);
		}
	}

}
